#include "window_config.h"
#include <iostream>
#include <fstream>
#include <glib.h>
#include <gtk/gtk.h>

// 静态成员变量定义
std::map<std::string, WindowConfig> WindowConfigManager::windowConfigs;

std::string WindowConfigManager::getConfigFilePath(const std::string& configFile) {
    char* execPath = g_file_read_link("/proc/self/exe", NULL);
    std::string configPath;
    
    if (execPath) {
        char* execDir = g_path_get_dirname(execPath);
        char* configFilePath;
        
        if (configFile.find("config/") == 0) {
            configFilePath = g_build_filename(execDir, configFile.c_str(), NULL);
        } else {
            configFilePath = g_build_filename(execDir, "config", configFile.c_str(), NULL);
        }
        
        configPath = configFilePath;
        g_free(configFilePath);
        g_free(execDir);
        g_free(execPath);
    } else {
        configPath = "config/" + configFile;
    }
    
    return configPath;
}

bool WindowConfigManager::loadWindowConfig(const std::string& configFile) {
    std::string configPath = getConfigFilePath(configFile);
    std::ifstream file(configPath);
    
    if (!file.is_open()) {
        std::cout << "窗口配置文件不存在，将使用默认配置: " << configPath << std::endl;
        return false;
    }
    
    std::string line;
    std::string currentSection;
    
    while (std::getline(file, line)) {
        // 去除首尾空白字符
        line.erase(0, line.find_first_not_of(" \t\r\n"));
        line.erase(line.find_last_not_of(" \t\r\n") + 1);
        
        // 跳过空行和注释
        if (line.empty() || line[0] == '#' || line[0] == ';') {
            continue;
        }
        
        // 检查节标题
        if (line[0] == '[' && line[line.size() - 1] == ']') {
            currentSection = line.substr(1, line.size() - 2);
            continue;
        }
        
        // 解析键值对
        size_t equalPos = line.find('=');
        if (equalPos != std::string::npos) {
            std::string key = line.substr(0, equalPos);
            std::string value = line.substr(equalPos + 1);
            
            // 去除键值中的空白字符
            key.erase(0, key.find_first_not_of(" \t"));
            key.erase(key.find_last_not_of(" \t") + 1);
            value.erase(0, value.find_first_not_of(" \t"));
            value.erase(value.find_last_not_of(" \t") + 1);
            
            if (!currentSection.empty()) {
                std::string fullKey = currentSection + "." + key;
                
                // 解析窗口配置
                if (key == "x") {
                    windowConfigs[currentSection].x = std::stoi(value);
                    windowConfigs[currentSection].is_set = true;
                } else if (key == "y") {
                    windowConfigs[currentSection].y = std::stoi(value);
                    windowConfigs[currentSection].is_set = true;
                } else if (key == "width") {
                    windowConfigs[currentSection].width = std::stoi(value);
                    windowConfigs[currentSection].is_set = true;
                } else if (key == "height") {
                    windowConfigs[currentSection].height = std::stoi(value);
                    windowConfigs[currentSection].is_set = true;
                } else if (key == "show") {
                    windowConfigs[currentSection].show = (value == "true" || value == "1");
                    windowConfigs[currentSection].is_set = true;
                }
            }
        }
    }
    
    file.close();
    std::cout << "成功加载窗口配置文件: " << configPath << std::endl;
    return true;
}

bool WindowConfigManager::saveWindowConfig(const std::string& configFile) {
    std::string configPath = getConfigFilePath(configFile);
    std::ofstream file(configPath);
    
    if (!file.is_open()) {
        std::cerr << "无法创建或写入窗口配置文件: " << configPath << std::endl;
        return false;
    }
    
    // 写入文件头
    file << "# 窗口配置信息\n";
    file << "# 自动生成的文件，请勿手动修改\n\n";
    
    // 写入每个窗口的配置
    for (const auto& pair : windowConfigs) {
        if (pair.second.is_set) {
            file << "[" << pair.first << "]\n";
            file << "x=" << pair.second.x << "\n";
            file << "y=" << pair.second.y << "\n";
            file << "width=" << pair.second.width << "\n";
            file << "height=" << pair.second.height << "\n";
            file << "show=" << (pair.second.show ? "true" : "false") << "\n\n";
        }
    }
    
    file.close();
    std::cout << "成功保存窗口配置文件: " << configPath << std::endl;
    return true;
}

WindowConfig WindowConfigManager::getWindowConfig(const std::string& windowName) {
    auto it = windowConfigs.find(windowName);
    if (it != windowConfigs.end()) {
        return it->second;
    }
    return WindowConfig();  // 返回默认配置
}

void WindowConfigManager::setWindowConfig(const std::string& windowName, const WindowConfig& config) {
    windowConfigs[windowName] = config;
}

gboolean WindowConfigManager::on_window_size_allocate(GtkWidget *widget, GtkAllocation *allocation, gpointer user_data) {
    std::string* windowName = static_cast<std::string*>(user_data);
    
    if (windowName && GTK_IS_WINDOW(widget)) {
        // 获取窗口的实际位置和大小
        gint x, y;
        gint width, height;
        
        gtk_window_get_position(GTK_WINDOW(widget), &x, &y);
        gtk_window_get_size(GTK_WINDOW(widget), &width, &height);
        
        // 更新配置
        WindowConfig config(x, y, width, height);
        setWindowConfig(*windowName, config);
    }
    
    return FALSE;  // 允许事件继续传播
}

void WindowConfigManager::applyWindowConfig(GtkWidget* window, const std::string& windowName) {
    if (!GTK_IS_WINDOW(window)) {
        return;
    }
    
    WindowConfig config = getWindowConfig(windowName);
    
    if (config.is_set) {
        // 应用配置到窗口
        gtk_window_move(GTK_WINDOW(window), config.x, config.y);
        gtk_window_resize(GTK_WINDOW(window), config.width, config.height);
        
        std::cout << "应用窗口配置: " << windowName 
                  << " x=" << config.x << " y=" << config.y 
                  << " width=" << config.width << " height=" << config.height << std::endl;
    } else {
        std::cout << "窗口配置不存在，使用默认设置: " << windowName << std::endl;
    }
    
    // 连接size-allocate信号以保存窗口大小和位置变化
    std::string* nameCopy = new std::string(windowName);
    g_signal_connect(window, "size-allocate", G_CALLBACK(on_window_size_allocate), nameCopy);
    
    // 连接destroy信号以保存配置并清理内存
    g_signal_connect(window, "destroy", G_CALLBACK(+[](GtkWidget* widget, gpointer data) {
        std::string* name = static_cast<std::string*>(data);
        if (name) {
            // 保存窗口配置
            saveWindowConfig("winCfg.ini");
            // 清理内存
            delete name;
        }
    }), nameCopy);
}